/*globals $, LOCK5MAIN */

LOCK5MAIN.buttons = ["#lower-tail-manual-percentage-button",
    "#middle-manual-percentage-button",
    "#upper-tail-manual-percentage-button",
    "#upper-tail-cutoff-button",
    "#lower-tail-cutoff-button"];

$.extend({
    createDotplot: function(specifier) {
        //define all the globals
        var LOWERTAILDEFAULT = 0.025, UPPERTAILDEFAULT = 0.975, GRID = {
            tickColor: "#eee",
            hoverable: true
        }, graphId = specifier.id, plotObject = {}, percentSubmitCallback, highlight = function() {
            $("#bootstrap-plot").effect("highlight", {
                color: "#eee"
            }, 350);
        };
        plotObject.currentLowerTail = LOWERTAILDEFAULT;
        plotObject.currentUpperTail = UPPERTAILDEFAULT;

        // Tail controls
        $("<div>").attr({
            id: "tail-controls"
        }).addClass("floatclear").appendTo("body");

        $.each([{
            id: "left-control",
            title: "Left Tail"
        },{
            id: "two-tail-control",
            title: "Two-Tail"
        },{
            id: "right-control",
            title: "Right Tail"
        }], function(i, attrs) {
            $('<input class="ui-widget" type="checkbox" id="' + attrs.id + '" \/><label class="ui-priority-primary ui-widget ui-widget-content" for="' + attrs.id + '">' + attrs.title + '<\/label>').appendTo("#tail-controls");
        });
        $("#tail-controls").css("position", "absolute");
        $("#tail-controls").css({
            left: $(specifier.id).offset().left + 25,
            top: $(specifier.id).offset().top + 10
        });

        //  tail controls (show/hide)
        $("#tail-controls input").click( function(e) {
            // this function will get executed every time the #home
            // element is clicked (or tab-spacebar changed)
            //Hide all the percent control buttons
            $(LOCK5MAIN.buttons.join(",")).hide();
            plotObject.plot(specifier.id, LOCK5MAIN.activeHistogram.histogramPoints);
            
        });
        
        $("#left-control,#right-control").change( function(e) {
             //Define behavior on tail controls so that if a lower/upper is clicked when two is on, turn it off
             if ($(this).attr("checked")) {
                 if ($("#two-tail-control").attr('checked')) {
                    $("#two-tail-control").attr('checked', false).button("refresh");
                    plotObject.currentLowerTail = LOWERTAILDEFAULT;
                    plotObject.currentUpperTail = UPPERTAILDEFAULT;
                 }
             }
             delete LOCK5MAIN.currentLowerCutoff;
             delete LOCK5MAIN.currentUpperCutoff;
        });
        $("#two-tail-control").change(function(e) {
            //If lower or upper is on when two is clicked, turn them off
            if ($(this).attr("checked")) {
                $("#left-control").attr('checked', false).button("refresh");
                $("#right-control").attr('checked', false).button("refresh");
            }
            plotObject.currentLowerTail = LOWERTAILDEFAULT;
            plotObject.currentUpperTail = UPPERTAILDEFAULT;
            delete LOCK5MAIN.currentLowerCutoff;
            delete LOCK5MAIN.currentUpperCutoff;
        });
        
        //callback for manual percentage
        percentSubmitCallback = function(dialog, buttonId, tailupdateFunction) {
            return function() {
                var percent, percentValid;
                percent = parseFloat($("#percentile", dialog).val());

                // validate
                percentValid = percent >= 0 && percent <= 1;
                if (!percentValid) {
                    $("#percentile", dialog).addClass("ui-state-error");
                    $(".validateTips", dialog).addClass("ui-state-highlight");
                } else {
                    $("#percentile", dialog).removeClass("ui-state-error");
                    $(".validateTips", dialog).removeClass("ui-state-highlight");
                    buttonId.button("option", "label", percent);
                    tailupdateFunction(percent);
                    
                    //remove tail cutoffs if they exist
                    delete LOCK5MAIN.currentLowerCutoff;
                    delete LOCK5MAIN.currentUpperCutoff;
                    
                    plotObject.plot(specifier.id, LOCK5MAIN.activeHistogram.histogramPoints);
                    highlight();
                    dialog.dialog("close");
                }
                return false;
            };
        };
        // create manual percentage button functionality
        $.each([{
            id: "lower-tail-manual-percentage-button",
            callback: function(percent) {
                if ($("#left-control").is(":checked")) {
                    plotObject.currentLowerTail = percent;
                    //check to see if the percent overlaps the upper tail, if so go up to it, but not past it
                    if (plotObject.currentLowerTail > plotObject.currentUpperTail) {
                        if (($("#right-control").is(":checked") || $("#two-tail-control").is(":checked"))) {
                            plotObject.currentLowerTail = plotObject.currentUpperTail;
                        } else {
                            //this handles the case when the control is turned off, so when it's
                            //turned on it doesn't automatically overlap
                            plotObject.currentUpperTail = plotObject.currentLowerTail;
                        }
                    }
                } else {
                    //two tail functionality is on.  doesn't make sense to go larger than 50%
                    if (percent > 0.5) {
                        percent = 0.5;
                    }
                    var centerPercent = 1 - percent * 2;
                    plotObject.currentLowerTail = (1 - centerPercent) / 2;
                    plotObject.currentUpperTail = plotObject.currentLowerTail + centerPercent;
                }
            }
        },{
            id: "upper-tail-manual-percentage-button",
            callback: function(percent) {
                if ($("#right-control").is(":checked")) {
                    //check to see if the percent overlaps the upper tail, if so go up to it, but not past it
                    plotObject.currentUpperTail = 1 - percent;
                    if (plotObject.currentLowerTail > plotObject.currentUpperTail) {
                        if ($("#left-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                            plotObject.currentUpperTail = plotObject.currentLowerTail;
                        } else {
                            //this handles the case when the control is turned off, so when it's
                            //turned on it doesn't automatically overlap
                            plotObject.currentLowerTail = plotObject.currentUpperTail;
                        }
                    }
                } else {
                    //two tail functionality is on.  doesn't make sense to go larger than 50%
                    if (percent > 0.5) {
                        percent = 0.5;
                    }
                    var centerPercent = 1 - percent * 2;
                    plotObject.currentLowerTail = (1 - centerPercent) / 2;
                    plotObject.currentUpperTail = plotObject.currentLowerTail + centerPercent;
                }
            }
        },{
            id: "middle-manual-percentage-button",
            callback: function(percent) {
                var centerPercent = percent;
                plotObject.currentLowerTail = (1 - centerPercent) / 2;
                plotObject.currentUpperTail = plotObject.currentLowerTail + centerPercent;
            }
        }], function(i, val) {
            var button = $('<button>').attr("id", val.id).button().click(( function() {
                var form = $('<div id="custom-percentile-form"><p class="validateTips">Enter a proportion (between 0.0 and 1.0).<\/p><form><label for="percentile">Proportion<\/label><input type="text" name="percentile" id="percentile" class="text ui-widget-content ui-corner-all"\/><\/form><\/div>');
                form.dialog({
                    autoOpen: false,
                    title: "Custom Proportion",
                    modal: true,
                    show: {
                        effect: "fade",
                        speed: "fast"
                    },
                    hide: {
                        effect: "fade",
                        speed: "fast"
                    },
                    buttons: [{
                        text: "Ok (or hit Enter)",
                        click: percentSubmitCallback(form, $(val.percentId), val.callback)
                    }]
                });
                form.submit(percentSubmitCallback(form, $(val.percentId), val.callback));
                return function() {
                    form.dialog('open');
                    $("#percentile", form).select().focus();
                    return false;
                };
            }()));
            $('body').append(button);
        });
        
        plotObject.balanceCutoffs = function(cutoff,buttonObjects,i) {
            var index, a, ap, b, bp;
            // sort the points by x position, then y position
            LOCK5MAIN.activeHistogram.histogramPoints.sort( function(a, b) {
                return a[3] - b[3];
            });
            index = $.binarySearch(LOCK5MAIN.activeHistogram.histogramPoints, cutoff, 3);
            //if too small or large, clamp cutoff to actual value
            if (index <= 0) {
                cutoffPercent = 0;
            } else if (index >= LOCK5MAIN.activeHistogram.histogramPoints.length - 1) {
                cutoffPercent = 1;
            } else {
                //otherwise, interpolate the two points between the cutoff
                a = LOCK5MAIN.activeHistogram.histogramPoints[index][3];
                b = LOCK5MAIN.activeHistogram.histogramPoints[index - 1][3];
                ap = index / LOCK5MAIN.activeHistogram.histogramPoints.length;
                bp = (index - 1) / LOCK5MAIN.activeHistogram.histogramPoints.length;
                cutoffPercent = ap;
                if (a !== b) {
                    cutoffPercent = $.linearInterpolate(a, b, ap, bp, cutoff);
                }
            }
            
            if ($("#two-tail-control").is(":checked")) {
                //if twotail mode is on, make sure we don't pass the middle.
                if ((i === 0 && cutoffPercent > 0.5) || (i === 1 && cutoffPercent < 0.5)) {
                    cutoffPercent = 0.5;
                }
                //adjust both tails, whatever the current value of i is, use that percentage directly
                //invert the other
                buttonObjects[i].callback(cutoffPercent,cutoff);
                buttonObjects[(i+1)%2].callback(1-cutoffPercent);
            } else {
                buttonObjects[i].callback(cutoffPercent, cutoff);
            }
        };
        
        // Cutoff button functionality, when button is clicked a callback
        // determines the cutoff percentage.  each button knows which tail it belongs to
        $(function() {
            plotObject.buttonObjects = [{
                id: "lower-tail-cutoff-button",
                callback: function(percent,cutoff) {
                    if (cutoff) {
                        LOCK5MAIN.currentLowerCutoff = cutoff;
                    } else {
                        delete LOCK5MAIN.currentLowerCutoff;
                    }
                    plotObject.currentLowerTail = percent;
                    if (plotObject.currentLowerTail < 0.0) {
                        plotObject.currentLowerTail = 0.0;
                    }
                    if (plotObject.currentUpperTail < plotObject.currentLowerTail) {
                        if ($("#right-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                            plotObject.currentLowerTail = plotObject.currentUpperTail;
                        } else {
                            plotObject.currentUpperTail = plotObject.currentLowerTail;
                        }
                    }
                }
            },{
                id: "upper-tail-cutoff-button",
                callback: function(percent,cutoff) {
                    if (cutoff) {
                        LOCK5MAIN.currentUpperCutoff = cutoff;
                    } else {
                        delete LOCK5MAIN.currentUpperCutoff;
                    }
                    plotObject.currentUpperTail = percent;
                    if (plotObject.currentUpperTail > 1.0) {
                        plotObject.currentUpperTail = 1.0;
                    }
                    if (plotObject.currentUpperTail < plotObject.currentLowerTail) {
                        if ($("#left-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                            plotObject.currentUpperTail = plotObject.currentLowerTail;
                        } else {
                            plotObject.currentLowerTail = plotObject.currentUpperTail;
                        }
                    }
                }
            }];
            
            $.each(plotObject.buttonObjects, function(i, buttonType) {
                var button = $("<button>").attr("id", buttonType.id).button().click(( function() {
                    var form = $('<div id="custom-cutoff-form"><p class="validateTips">Enter a numerical cutoff value<\/p><form><label for="cutoff">Cutoff<\/label><input type="text" name="cutoff" id="cutoff" class="text ui-widget-content ui-corner-all"\/><\/form><\/div>'), cutoffSubmitCallback = function(dialog) {
                        return function() {
                            var cutoff, cutoffPercent, cutoffValid, index, a, ap, b, bp;
                            cutoff = parseFloat($("#cutoff", dialog).val());
                            cutoffValid = !isNaN(cutoff);
                            // validate
                            if (!cutoffValid) {
                                $("#cutoff", dialog).addClass("ui-state-error");
                                $(".validateTips", dialog).addClass("ui-state-highlight");
                            } else {
                                plotObject.balanceCutoffs(cutoff,plotObject.buttonObjects,i);
                                
                                plotObject.plot(specifier.id, LOCK5MAIN.activeHistogram.histogramPoints);
                                dialog.dialog("close");
                            }
                            return false;
                        };
                    };
                    form.dialog({
                        autoOpen: false,
                        title: "Custom Cutoff",
                        modal: true,
                        show: {
                            effect: "fade",
                            speed: "fast"
                        },
                        hide: {
                            effect: "fade",
                            speed: "fast"
                        },
                        buttons: [{
                            text: "Ok (or hit Enter)",
                            click: cutoffSubmitCallback(form)
                        }]
                    });
                    form.submit(cutoffSubmitCallback(form));
                    return function() {
                        form.dialog('open');
                        $("#cutoff", form).focus().select();
                        return false;
                    };
                }()));
                $('body').append(button);
            });
        });
        //define functions
        plotObject.clear = function() {
            //Hide all the percent cutoff and manual cutoff buttons
            $(LOCK5MAIN.buttons.join(",")).hide();

            $("#left-control").attr('checked', false).button("refresh");
            $("#two-tail-control").attr('checked', false).button("refresh");
            $("#right-control").attr('checked', false).button("refresh");

            plotObject.currentUpperTail = UPPERTAILDEFAULT;
            plotObject.currentLowerTail = LOWERTAILDEFAULT;
            $("#upper-tail-manual-percentage-button").button({
                label: Math.truncate(1 - plotObject.currentUpperTail, 3)
            });
            $("#lower-tail-manual-percentage-button").button({
                label: Math.truncate(plotObject.currentLowerTail, 3)
            });
            delete LOCK5MAIN.currentLowerCutoff;
            delete LOCK5MAIN.currentUpperCutoff;
            plotObject.plot(graphId, []);
            return true;
        };
        plotObject.arrowAnnotation = function(plot, x, text, color) {
            var offset, arrowHeight, arrowWidth, textWidth, canvasContext;

            arrowHeight = 20;
            arrowWidth = 6;
            offset = plot.pointOffset({
                x: x,
                y: 0
            });

            textWidth = $.calculateSize(text).width;

            plot.getPlaceholder().append("<div class=\"arrow-label\" class=\"ui-dialog-content\" style=\"position:absolute;left:" + (offset.left - textWidth / 2) + "px;top:" + (offset.top + arrowHeight) + "px;\">" + text + "<\/div>");

            // This part does the little arrow drawing
            canvasContext = plot.getCanvas().getContext("2d");
            canvasContext.beginPath();
            canvasContext.moveTo(offset.left, offset.top);
            canvasContext.lineTo(offset.left - arrowWidth / 2, offset.top + arrowHeight);
            canvasContext.lineTo(offset.left + arrowWidth / 2, offset.top + arrowHeight);
            canvasContext.lineTo(offset.left, offset.top);
            canvasContext.fillStyle = color;
            canvasContext.fill();
        };
        plotObject.setBounds = function(bounds) {
            plotObject.graphProperties = {
                xaxis: $.extend(true, {}, bounds.xaxis),
                xaxisDefault: $.extend(true, {}, bounds.xaxis),
                yaxis: $.extend(true, {}, bounds.yaxis),
                yaxisDefault: $.extend(true, {}, bounds.yaxis),
                grid: {
                    tickColor: GRID.tickColor,
                    hoverable: GRID.hoverable
                }
            };
        };
        
        plotObject.plot = function(graphId, xyPoints) {
            var percentTop, offsetLeft, offsetRight, tmpPoints, meanLabel, leftTail, rightTail, points, stdevLabel, stdevX, xlist, CENTRALCOLOR, LEFTCOLOR, RIGHTCOLOR, plot, bootstrapPlot, meanX, leftCutoff, rightCutoff, leftCutoffIndex, rightCutoffIndex, leftCutoffPercent, leftCutoff_lower, leftCutoffPercent_lower, rightCutoffPercent, rightCutoff_lower, rightCutoffPercent_lower, interpolatedCutoff;

            if (LOCK5MAIN.hypothesisTest) {
                if (LOCK5MAIN.currentUpperCutoff) {
                    plotObject.balanceCutoffs(LOCK5MAIN.currentUpperCutoff,plotObject.buttonObjects,1);
                }
                if (LOCK5MAIN.currentLowerCutoff) {
                    plotObject.balanceCutoffs(LOCK5MAIN.currentLowerCutoff,plotObject.buttonObjects,0);
                }
            }
            
            LEFTCOLOR = "#f00";
            RIGHTCOLOR = "#f00";
            CENTRALCOLOR = "#000";

            // Determine whether to show the tails based on the global
            // visibility of the tail controls
            rightCutoffIndex = xyPoints.length;
            if ($("#right-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                rightCutoffIndex = Math.floor(xyPoints.length * plotObject.currentUpperTail);
                // make central black if there is a tail
                CENTRALCOLOR = "#000";
            }
            leftCutoffIndex = 0;
            if ($("#left-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                leftCutoffIndex = Math.ceil(xyPoints.length * (plotObject.currentLowerTail));
                // make central black if there is a tail
                CENTRALCOLOR = "#000";
            }

            // sort the points by x position, then y position
            xyPoints.sort( function(a, b) {
                return a[0] !== b[0] ? (a[0] - b[0]) : (a[1] - b[1]);
            });
            // break xyPoints into three categories, left, right, central
            points = LOCK5MAIN.formatPoints(xyPoints.slice(leftCutoffIndex, rightCutoffIndex), CENTRALCOLOR, "$\\# samples = " + xyPoints.length + "$");
            leftTail = LOCK5MAIN.formatPoints(xyPoints.slice(0, leftCutoffIndex), LEFTCOLOR);
            rightTail = LOCK5MAIN.formatPoints(xyPoints.slice(rightCutoffIndex), RIGHTCOLOR);

            xlist = $.map(xyPoints, function(pair) {
                return pair[3];
            });
            // Standard stats calculations
            meanX = $.mean(xyPoints, 3);
            stdevX = $.stdev(xyPoints, 3);
            stdevLabel = LOCK5MAIN.formatPoints([], CENTRALCOLOR, "$st. dev. = " + Math.truncate(stdevX, 3)+"$");
            meanLabel = LOCK5MAIN.formatPoints([], CENTRALCOLOR, "$mean = " + Math.truncate(meanX, 3) + "$");

            //See if we need to adjust x or y
            if (xyPoints.length > 0) {
                ( function() {
                    var xRange = $.findMinMax(xyPoints, 0), yRange = $.findMinMax(xyPoints, 1);
                    if (xRange.max > plotObject.graphProperties.xaxis.max) {
                        //the * 1.1 makes the graph grow a little larger than it needs to
                        plotObject.graphProperties.xaxis.max = xRange.max;
                    }
                    if (xRange.min < plotObject.graphProperties.xaxis.min) {
                        plotObject.graphProperties.xaxis.min = xRange.min;
                    }
                    if (yRange.max > plotObject.graphProperties.yaxis.max) {
                        plotObject.graphProperties.yaxis.max = yRange.max * 1.1;
                    }
                    if (plotObject.graphProperties.xaxis.max < LOCK5MAIN.currentUpperCutoff) {
                        plotObject.graphProperties.xaxis.max = LOCK5MAIN.currentUpperCutoff;
                    }
                    if (plotObject.graphProperties.xaxis.min > LOCK5MAIN.currentLowerCutoff) {
                        plotObject.graphProperties.xaxis.min = LOCK5MAIN.currentLowerCutoff;
                    }
                    //ignore y min, don't make y go negative here...'
                }());
            }

            // Generate the plot and grab the resulting plot object
            // If only one point, plot it right on its mean
            if (xyPoints.length === 1) {
                tmpPoints = {
                    color: points.color,
                    data: [[xyPoints[0][3], xyPoints[0][1], xyPoints[0][2], xyPoints[0][3]]],
                    label: points.label,
                    shadowSize: 1,
                    points: points.points
                };
                plot = $.plot($(graphId), [tmpPoints, meanLabel, stdevLabel], plotObject.graphProperties);
            } else {
                plot = $.plot($(graphId), [points, leftTail, rightTail, meanLabel, stdevLabel], plotObject.graphProperties);
            }
            bootstrapPlot = $(specifier.id);
            if (xyPoints.length > 0) {
                // plot the mean arrow
                specifier.graphAnnotation(plotObject.arrowAnnotation, plot, xyPoints);
                percentTop = $(specifier.id).offset().top + $(specifier.id).height() / 2;

                // plot right tail arrow
                if ($("#right-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                    rightCutoffIndex = Math.ceil(xyPoints.length * plotObject.currentUpperTail);
                    if (rightCutoffIndex >= xlist.length) {
                        //since it's the far right, get its bin value so the arrow looks good,
                        //not its actual value
                        interpolatedCutoff = $.selection($.map(xyPoints, function(pair) {
                            return pair[0];
                        }), xlist.length - 1);
                    } else if (rightCutoffIndex <= 0) {
                        //since it's the far left, get its bin value so the arrow looks good,
                        //not its actual value
                        interpolatedCutoff = $.selection($.map(xyPoints, function(pair) {
                            return pair[0];
                        }), 0);
                    } else {
                        rightCutoff = $.selection(xlist, rightCutoffIndex);
                        rightCutoffPercent = rightCutoffIndex / xyPoints.length;
                        rightCutoff_lower = $.selection(xlist, rightCutoffIndex - 1);
                        rightCutoffPercent_lower = (rightCutoffIndex - 1) / xyPoints.length;
                        interpolatedCutoff = $.linearInterpolate(rightCutoffPercent_lower, rightCutoffPercent, rightCutoff_lower, rightCutoff, plotObject.currentUpperTail);
                    }
                    if (LOCK5MAIN.currentUpperCutoff) {
                        interpolatedCutoff = LOCK5MAIN.currentUpperCutoff;
                    }
                    plotObject.arrowAnnotation(plot, interpolatedCutoff, "", RIGHTCOLOR);
                    offsetRight = plot.pointOffset({
                        x: interpolatedCutoff,
                        y: 0
                    });
                    $("#upper-tail-manual-percentage-button").css({
                        position: 'absolute',
                        left: offsetRight.left + $("#upper-tail-manual-percentage-button").width(),
                        top: percentTop
                    }).show().button({
                        label: Math.truncate(1 - plotObject.currentUpperTail, 3)
                    });
                    $("#upper-tail-cutoff-button").button({
                        label: Math.truncate(interpolatedCutoff, 3)
                    }).css({
                        position: 'absolute',
                        left: $(specifier.id).offset().left + offsetRight.left - 10,
                        top: $(specifier.id).offset().top + $(specifier.id).height()
                    }).show();
                }

                // plot left tail arrow
                if ($("#left-control").is(":checked") || $("#two-tail-control").is(":checked")) {
                    leftCutoffIndex = Math.floor(xyPoints.length * (plotObject.currentLowerTail));
                    if (leftCutoffIndex <= 0) {
                        interpolatedCutoff = $.selection($.map(xyPoints, function(pair) {
                            return pair[0];
                        }), 0);
                    } else if (leftCutoffIndex >= xyPoints.length) {
                        //since it's the far left, get its bin value so the arrow looks good,
                        //not its actual value
                        interpolatedCutoff = $.selection($.map(xyPoints, function(pair) {
                            return pair[0];
                        }), xyPoints.length - 1);
                    } else {
                        leftCutoff = $.selection(xlist, leftCutoffIndex);
                        leftCutoffPercent = leftCutoffIndex / xyPoints.length;
                        leftCutoff_lower = $.selection(xlist, leftCutoffIndex + 1);
                        leftCutoffPercent_lower = (leftCutoffIndex + 1) / xyPoints.length;
                        interpolatedCutoff = $.linearInterpolate(leftCutoffPercent_lower, leftCutoffPercent, leftCutoff_lower, leftCutoff, plotObject.currentLowerTail);
                    }
                    if (LOCK5MAIN.currentLowerCutoff) {
                        interpolatedCutoff = LOCK5MAIN.currentLowerCutoff;
                    }
                    offsetLeft = plot.pointOffset({
                        x: interpolatedCutoff,
                        y: 0
                    });
                    plotObject.arrowAnnotation(plot, interpolatedCutoff, "", LEFTCOLOR);
                    $("#lower-tail-manual-percentage-button").button({
                        label: Math.truncate(plotObject.currentLowerTail, 3)
                    }).css({
                        position: 'absolute',
                        left: offsetLeft.left,
                        top: percentTop
                    }).show();
                    $("#lower-tail-cutoff-button").button({
                        label: Math.truncate(interpolatedCutoff, 3)
                    }).css({
                        position: 'absolute',
                        left: $(specifier.id).offset().left + offsetLeft.left - $("#lower-tail-cutoff-button").width() + 10,
                        top: $(specifier.id).offset().top + $(specifier.id).height()
                    }).show();
                }

                // plot the mean and center percent
                if ($("#two-tail-control").is(":checked") || ($("#left-control").is(":checked") && $("#right-control").is(":checked"))) {
                    $("#middle-manual-percentage-button").button({
                        label: Math.truncate(plotObject.currentUpperTail - plotObject.currentLowerTail, 3)
                    }).css({
                        position: 'absolute',
                        left: $(specifier.id).offset().left + (offsetLeft.left + offsetRight.left) / 2 - $("#middle-manual-percentage-button").width() / 2,
                        top: percentTop
                    }).show();
                }
            }
            MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
        };
        return plotObject;
    }
});